import React, { useState, useEffect, useRef } from "react";
import { Alert, Form, Switch, Input, Button, Typography, InputNumber } from "antd";
import CommonTable from "@/components/CommonTable";
import CommonInputNumber from "@/pages/OrderModule/common/components/CommonInputNumber";
import { speak } from "@/utils/utils.jsx";
import { getCurrentUser } from "@/utils/authority";
import { getOutboundorderweighList, orderWeigh } from "./service";
const { Text, Link } = Typography;
const storage = window.localStorage; //全局的本地缓存
const WeighDelivery = () => {
	const [form] = Form.useForm();
	const [tableList, setTableList] = useState([]);
	const isModifyWeightValue = Form.useWatch("isModifyWeight", form);
	const RefInputWeight = useRef(null);
	const RefInputNo = useRef(null);
	const RefHiddenNo = useRef(null);

	const titleSpan = title => <span className="font18">{title}</span>;

	const columns = [
		{
			title: titleSpan("出库单号"),
			dataIndex: "outboundNo",
			render: text => {
				return titleSpan(text);
			}
		},
		{
			title: titleSpan("快递物流单号"),
			dataIndex: "waybillNo",
			render: text => {
				return titleSpan(text);
			}
		},
		{
			title: titleSpan("预计运费（元）"),
			dataIndex: "estimateFreight",
			render: text => {
				return titleSpan(text);
			}
		},
		{
			title: titleSpan("实际重量（kg）"),
			dataIndex: "actualWeight",
			render: text => {
				return titleSpan(text);
			}
		},
		{
			title: titleSpan("支付运费（元）"),
			dataIndex: "payFreight",
			render: text => {
				return (
					<Text type="danger" className="font18">
						{text}
					</Text>
				);
			}
		},
		{
			title: titleSpan("称重状态"),
			dataIndex: "weighStatus",
			render: text => {
				return (
					<Text type={text?.includes("失败") ? "danger" : "success"} className="font18">
						{text}
					</Text>
				);
			}
		},
		{
			title: titleSpan("失败原因说明"),
			dataIndex: "failReason",
			render: text => {
				return titleSpan(text);
			}
		}
	].map(item => {
		return {
			...item,
			key: item.dataIndex
		};
	});
	// 回车事件
	async function commonPressEnter(value, type) {
		// 是否重量
		const isWeight = type === "weight";
		if (value && !isWeight) {
			orderWeighFn(isWeight);
		}
		if (value && isWeight) {
			orderWeighFn(isWeight);
		}
	}
	async function orderWeighFn(isWeight) {
		const { waybillNo, actualWeight } = form.getFieldsValue();
		const isVoice = storage[getCurrentUser()?.id] && JSON.parse(storage[getCurrentUser().id]);
		const { success, data, msg } = await orderWeigh({
			waybillNo,
			actualWeight,
			isWeight,
			outboundOrderWeighDtoList: tableList
		});
		console.log(data, msg);
		if (success) {
			if (!isWeight) {
				RefInputWeight.current.focus();
			} else {
				form.resetFields();
				RefInputNo.current.focus();
			}
			setTableList(data);
			// data 返回是否称重： 未称重：true，已称重：false
			// 已称重
			const weighStatus = data[data.length - 1].weighStatus;
			if (weighStatus === "失败") {
				/**
				 * 若查询到出库单号再去判断是否称重过，若称重过，列表展示对应的出库单号，物流单号重量等信息，称重状态为称重失败，原因为该订单已称重，同时播报语音： * 该订单已称重
				 * 当未查询到或者查询到是已经称重过的订单时，对应的快递单号输入框数据清空，光标在快递输入框内可以直接再次输入或者扫描新的数据
				 */
				// 已称重获取列表数据
				if (isVoice) speak({ text: "该订单已称重" });
				reset();
			}
		} else {
			if (isVoice) speak({ text: msg });
			reset();
		}
	}
	// 键盘事件监听
	const scanRequest = e => {
		if (window.location.hash == "#/views/StockManage/WeighDelivery") {
			const { key } = e;
			switch (key) {
				case "F1":
					// 重置(F1)
					reset();
					break;
				default:
					break;
			}
		}
	};

	const reset = () => {
		form.resetFields();
		setTimeout(() => {
			RefInputNo.current.focus();
		}, 10);
	};

	// 阻止默认事件
	const prevent = e => {
		if (window.location.hash == "#/views/StockManage/WeighDelivery") {
			if (["F1"].includes(e.key)) {
				e.preventDefault();
			}
		}
	};
	
	//监听键盘事件,阻止默认事件
	useEffect(() => {
		window.addEventListener("keydown", prevent, false);
		window.addEventListener("keyup", scanRequest, false);
		return () => {
			window.removeEventListener("keydown", prevent, false);
			window.removeEventListener("keyup", scanRequest, false);
		};
	}, []);

	useEffect(() => {
		// RefInputNo.current.focus();
	}, []);
	const tableProps = {
		data: tableList,
		columns
	};

	return (
		<div className="zjf-container" style={{ height: "100%", background: "#fff", padding: 16 }}>
			<Alert message="需要连接电子秤，请先称重再扫描运单号" showIcon type="info" style={{ marginBottom: "16px" }} />
			<Form form={form}>
				<div className="flex">
					<Form.Item name="waybillNo">
						<Input
							ref={RefInputNo}
							placeholder="请输入快递单号"
							onPressEnter={e => commonPressEnter(e.target.value, "OrderNo")}
							style={{ height: 40, width: 262 }}
						/>
					</Form.Item>
					<Form.Item>
						<Button
							onClick={() => {
								reset();
								setTableList([]);
							}}
							style={{ marginLeft: 16, width: 72, height: 40 }}
						>
							重置(F1)
						</Button>
					</Form.Item>
				</div>
				<div className="flex align-items">
					<Form.Item name="actualWeight">
						<InputNumber
							ref={RefInputWeight}
							min={0}
							max={100000000}
							precision={2}
							controls={false}
							onPressEnter={e => commonPressEnter(e.target.value, "weight")}
							autoFocus
							placeholder="请扫描/输入包裹重量"
							disabled={!isModifyWeightValue}
							style={{ height: 40, width: 262, lineHeight: "40px" }}
						/>
					</Form.Item>

					<Form.Item label="是否允许手动修改重量：" name="isModifyWeight" style={{ marginLeft: "16px" }}>
						<Switch size="default" />
					</Form.Item>
				</div>
				<Form.Item label="称重失败语音提醒：" name="isVoice">
					<Switch
						size="default"
						defaultChecked={(storage[getCurrentUser()?.id] && JSON.parse(storage[getCurrentUser().id])) || false}
						onChange={e => {
							storage[getCurrentUser().id] = e;
						}}
					/>
				</Form.Item>

				<Form.Item name="hiddenNo">
					<Input ref={RefHiddenNo} style={{ display: "none" }} />
				</Form.Item>
			</Form>
			<CommonTable bordered {...tableProps} />
		</div>
	);
};

export default React.memo(WeighDelivery, () => {
	return true;
});
